package crowdedroom.hop4droid;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;

import android.content.Context;

/**
 * The Class FilePersister.
 */
public class FilePersister {
  /**
   * The Constant FILE.
   */
  public static final String FILE = "exceptions.xml";
  /**
   * Clear.
   * @param context the context
   */
  public static void clear(final Context context) {
    try {
      context.deleteFile(FILE);
    } catch (final Exception e) {
      // swallow
    }
  }
  /**
   * Read.
   * @param context the context
   * @return the string[]
   */
  public static String[] read(final Context context) {
    BufferedInputStream input = null;
    final StringBuilder sb = new StringBuilder();
    try {
      input = new BufferedInputStream(context.openFileInput(FILE));
      int line;
      while ((line = input.read()) > 0) {
        sb.append((char) line);
      }
    } catch (final Exception e) {
      // Swallow
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (final Exception ignored) {
          // Swallow
        }
      }
    }
    final String contents = sb.toString();
    final String[] results = contents.split("</notice>");
    for (int i = 0; i < results.length; i++) {
      results[i] =
        new StringBuilder(results[i]).append("</notice>").toString();
    }
    return results;
  }
  /**
   * Save.
   * @param context the context
   * @param xml the xml
   * @param overwrite the overwrite
   */
  public static void save(
    final Context context,
    final String xml,
    final boolean overwrite) {
    FileOutputStream output = null;
    int mode = Context.MODE_APPEND;
    if (overwrite) {
      mode = Context.MODE_PRIVATE;
    }
    try {
      output = context.openFileOutput(FILE, mode);
      output.write(xml.getBytes());
    } catch (final Exception e) {
      // Swallow
    } finally {
      try {
        if (output != null) {
          output.close();
        }
      } catch (final Exception e) {
        // Swallow
      }
    }
  }
}
